from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import RegulationService
from app.utils.decorators import admin_required

regulation_services_bp = Blueprint('regulation_services', __name__)

@regulation_services_bp.route('/', methods=['GET'])
@jwt_required()
@admin_required
def get_regulation_services():
    """获取调节服务数据列表"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    # 获取搜索参数
    year = request.args.get('year', '')
    gep_city = request.args.get('gepCity', '')
    gep_district = request.args.get('gepDistrict', '')
    gep_town = request.args.get('gepTown', '')
    
    query = RegulationService.query
    
    # 根据搜索条件过滤
    if year:
        query = query.filter(RegulationService.year == year)
    if gep_city:
        query = query.filter(RegulationService.gepCity.contains(gep_city))
    if gep_district:
        query = query.filter(RegulationService.gepDistrict.contains(gep_district))
    if gep_town:
        query = query.filter(RegulationService.gepTown.contains(gep_town))
    
    # 限制最多返回100条数据
    total_count = query.count()
    if total_count > 100:
        # 如果总数超过100，调整分页参数
        per_page = min(per_page, 100)
        page = min(page, (total_count + per_page - 1) // per_page)
    
    pagination = query.paginate(
        page=page, per_page=per_page, error_out=False
    )
    
    services = pagination.items
    
    return jsonify({
        'regulation_services': [service.to_dict() for service in services],
        'pagination': {
            'page': page,
            'per_page': per_page,
            'total': min(pagination.total, 100),
            'pages': pagination.pages
        }
    }), 200

@regulation_services_bp.route('/<int:service_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_regulation_service(service_id):
    """获取单个调节服务数据详情"""
    service = RegulationService.query.get(service_id)
    if not service:
        return jsonify({'message': '数据不存在'}), 404
    
    return jsonify({
        'regulation_service': service.to_dict()
    }), 200

@regulation_services_bp.route('/', methods=['POST'])
@jwt_required()
@admin_required
def create_regulation_service():
    """创建调节服务数据"""
    current_user_id = get_jwt_identity()
    data = request.get_json()
    
    # 验证必填字段
    required_fields = ['year', 'gepCity', 'gepDistrict', 'gepTown']
    for field in required_fields:
        if not data.get(field):
            return jsonify({'message': f'字段 {field} 不能为空'}), 400
    
    # 检查唯一性约束
    existing = RegulationService.query.filter_by(
        year=data['year'],
        gepCity=data['gepCity'],
        gepDistrict=data['gepDistrict'],
        gepTown=data['gepTown']
    ).first()
    
    if existing:
        return jsonify({'message': '该地区该年份的调节服务数据已存在'}), 400
    
    # 创建新数据
    service = RegulationService(
        year=data['year'],
        gepCity=data['gepCity'],
        gepDistrict=data['gepDistrict'],
        gepTown=data['gepTown'],
        outWaterSourceConservation=data.get('outWaterSourceConservation'),
        outSoilConservation=data.get('outSoilConservation'),
        outNegativeOxygenIons=data.get('outNegativeOxygenIons'),
        outAirPurification=data.get('outAirPurification'),
        outWaterPurification=data.get('outWaterPurification'),
        outCarbonSequestration=data.get('outCarbonSequestration'),
        outOxygenRelease=data.get('outOxygenRelease'),
        outClimateRegulation=data.get('outClimateRegulation'),
        outCalcFloodRegulation=data.get('outCalcFloodRegulation'),
        outCalcBiodiversityProtection=data.get('outCalcBiodiversityProtection'),
        outCalcNoiseReduced=data.get('outCalcNoiseReduced'),
        creator=str(current_user_id)
    )
    
    try:
        db.session.add(service)
        db.session.commit()
        return jsonify({
            'message': '创建成功',
            'regulation_service': service.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建失败: {str(e)}'}), 500

@regulation_services_bp.route('/<int:service_id>', methods=['PUT'])
@jwt_required()
@admin_required
def update_regulation_service(service_id):
    """更新调节服务数据"""
    current_user_id = get_jwt_identity()
    service = RegulationService.query.get(service_id)
    
    if not service:
        return jsonify({'message': '数据不存在'}), 404
    
    data = request.get_json()
    
    # 允许更新的字段
    allowed_fields = [
        'outWaterSourceConservation', 'outSoilConservation', 'outNegativeOxygenIons',
        'outAirPurification', 'outWaterPurification', 'outCarbonSequestration',
        'outOxygenRelease', 'outClimateRegulation', 'outCalcFloodRegulation',
        'outCalcBiodiversityProtection', 'outCalcNoiseReduced'
    ]
    
    # 更新字段
    for field in allowed_fields:
        if field in data:
            setattr(service, field, data[field])
    
    service.updater = str(current_user_id)
    
    try:
        db.session.commit()
        return jsonify({
            'message': '更新成功',
            'regulation_service': service.to_dict()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新失败: {str(e)}'}), 500

@regulation_services_bp.route('/<int:service_id>', methods=['DELETE'])
@jwt_required()
@admin_required
def delete_regulation_service(service_id):
    """删除调节服务数据"""
    service = RegulationService.query.get(service_id)
    
    if not service:
        return jsonify({'message': '数据不存在'}), 404
    
    try:
        db.session.delete(service)
        db.session.commit()
        return jsonify({'message': '删除成功'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除失败: {str(e)}'}), 500